package com.weilele.leisure.video_factory.utils

import android.content.ContentUris
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Parcelable
import android.provider.MediaStore
import androidx.core.database.getIntOrNull
import androidx.core.database.getLongOrNull
import androidx.core.database.getStringOrNull
import com.weilele.mvvm.adapter.ignoreError
import com.weilele.mvvm.app
import kotlinx.parcelize.Parcelize

private val sLocalAudioColumns = arrayOf(
    MediaStore.Audio.Media._ID,  // 视频id
    MediaStore.Audio.Media.DATA,  // 视频路径
    MediaStore.Audio.Media.SIZE,  // 视频字节大小
    MediaStore.Audio.Media.DISPLAY_NAME,  // 视频名称 xxx.mp4
    MediaStore.Audio.Media.TITLE,  // 视频标题
    MediaStore.Audio.Media.DATE_ADDED,  // 视频添加到MediaProvider的时间
    MediaStore.Audio.Media.DATE_MODIFIED,  // 上次修改时间，该列用于内部MediaScanner扫描，外部不要修改
    MediaStore.Audio.Media.MIME_TYPE,  // 视频类型 Audio/mp4
    MediaStore.Audio.Media.DURATION,  // 视频时长
    MediaStore.Audio.Media.ARTIST,  // 艺人名称
    MediaStore.Audio.Media.ALBUM,  // 艺人专辑名称
    MediaStore.Audio.Media.ALBUM_ID,  // 艺人专辑名称
    MediaStore.Audio.Media.ARTIST_ID,  // 艺人专辑名称
    MediaStore.Audio.Media.BOOKMARK, // 上次视频播放的位置
)

@Parcelize
data class MediaAudioInfo(
    var id: Long,
    var uri: Uri,
    var coverUri: String? = null,
    var data: String? = null,
    var size: Long? = null,
    var displayName: String? = null,
    var title: String? = null,
    var dateAdded: Long? = null,
    var dateModified: Long? = null,
    var mimeType: String? = null,
    var duration: Long? = null,
    var artist: String? = null,
    var artistId: Long? = null,
    var album: String? = null,
    var albumId: Long? = null,
    var bookmark: Long? = null,
) : Parcelable {
    fun toJsonString(): String {
        return "AudioInfo{" +
                "id=" + id +
                ", data='" + data + '\'' +
                ", size=" + size +
                ", displayName='" + displayName + '\'' +
                ", title='" + title + '\'' +
                ", dateAdded=" + dateAdded +
                ", dateModified=" + dateModified +
                ", mimeType='" + mimeType + '\'' +
                ", duration=" + duration +
                ", artist='" + artist + '\'' +
                ", album='" + album + '\'' +
                ", bookmark=" + bookmark +
                '}'
    }
}

fun getLocalAudioInfo(): MutableList<MediaAudioInfo> {
    val mAudioInfos = mutableListOf<MediaAudioInfo>()
    val queryUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor? = app.contentResolver.query(
        queryUri, sLocalAudioColumns,
        "${MediaStore.Audio.Media.IS_MUSIC}=?", arrayOf("1"), null
    )
    if (cursor != null && cursor.moveToFirst()) {
        do {
            ignoreError {
                //region 过滤掉小于1k的音频
                val size = cursor.getLongOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE))
                if (size == null || size < 1024) {
                    return@ignoreError
                }
                val id = cursor.getLongOrNull(cursor.getColumnIndex(MediaStore.Audio.Media._ID))
                    ?: return@ignoreError
                //endregion
                val audioInfo = MediaAudioInfo(id, ContentUris.withAppendedId(queryUri, id))
                val data =
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !Environment.isExternalStorageLegacy()) {
                        cursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.RELATIVE_PATH))
                            ?: cursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
                    } else {
                        cursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
                    }
                val displayName =
                    cursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME))
                val title =
                    cursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))
                val dateAdded =
                    cursor.getLongOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED))
                val dateModified =
                    cursor.getLongOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.DATE_MODIFIED))
                val mimeType =
                    cursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE))
                val duration =
                    cursor.getLongOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))
                val artist =
                    cursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST))
                val album =
                    cursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM))
                val albumId =
                    cursor.getLongOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID))
                val artistId =
                    cursor.getLongOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID))
                val bookmark =
                    cursor.getLongOrNull(cursor.getColumnIndex(MediaStore.Audio.Media.BOOKMARK))
                if (albumId != null) {
                    audioInfo.coverUri = "content://media/external/audio/albumart/${albumId}"
                    /*          val albumCursor = app.contentResolver.query(
                                  MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                                  null,
                                  "${MediaStore.Audio.Albums._ID}=?",
                                  arrayOf("$albumId"),
                                  null
                              )
                              if (albumCursor != null && albumCursor.moveToFirst()) {
                                  do {
                                      val albumName =
                                          albumCursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Audio.AlbumColumns.ALBUM))
                                  } while (albumCursor.moveToNext())
                                  albumCursor.close()
                              }
                              val artistCursor = app.contentResolver.query(
                                  MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
                                  null,
                                  "${MediaStore.Audio.Artists._ID}=?",
                                  arrayOf("$artistId"),
                                  null
                              )
                              if (artistCursor != null && artistCursor.moveToFirst()) {
                                  do {
                                      val artistCursorName =
                                          artistCursor.getStringOrNull(cursor.getColumnIndex(MediaStore.Audio.ArtistColumns.ARTIST))
                                  } while (artistCursor.moveToNext())
                                  artistCursor.close()
                              }*/
                }
                audioInfo.id = id
                audioInfo.data = data
                audioInfo.size = size
                audioInfo.displayName = displayName
                audioInfo.title = title
                audioInfo.dateAdded = dateAdded
                audioInfo.dateModified = dateModified
                audioInfo.mimeType = mimeType
                audioInfo.duration = duration
                audioInfo.artist = artist
                audioInfo.album = album
                audioInfo.artistId = artistId
                audioInfo.albumId = albumId
                audioInfo.bookmark = bookmark
                mAudioInfos.add(audioInfo)
            }
        } while (cursor.moveToNext())
        cursor.close()
    }
    return mAudioInfos
}